//
//  CustomOpenGLView.m
//  CustomOpenGLViewTemplate
//
//  Created by Math Wrath on 7/18/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#include <OpenGL/gl.h>
#include <GLUT/GLUT.h>

#import "CustomOpenGLView.h"

@implementation CustomOpenGLView


- (id)initWithFrame:(NSRect)frameRect {

    if ((self = [super initWithFrame:frameRect]) != nil) {
		
        GLuint attributes[] =
		{
			NSOpenGLPFAWindow,
			NSOpenGLPFAAccelerated,
			NSOpenGLPFADoubleBuffer,
			NSOpenGLPFAColorSize, 24,
			NSOpenGLPFAAlphaSize, 8,
			NSOpenGLPFADepthSize, 24,
			NSOpenGLPFAMinimumPolicy, 0
		};
		
		_pixelFormat = [ [ NSOpenGLPixelFormat alloc ]
						initWithAttributes:
						(NSOpenGLPixelFormatAttribute*) attributes ];

    }
	
	_context = nil;
    return self;	
}



- (NSOpenGLContext *) openGLContext {
	
	if ( _context == nil) {
		_context = [ [ NSOpenGLContext alloc ]
					initWithFormat: _pixelFormat shareContext: nil ];
	}
	
	return ( _context );
}

- (void) lockFocus {
	
	[ super lockFocus ];
	
	NSOpenGLContext *cxt = [self openGLContext ];
	
	if ( [cxt view ] != self ) {
		[ cxt setView: self ];
	}
	
	[ cxt makeCurrentContext ];
}

- (void) prepareOpenGL {
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1, 1, -1, 1, -1, 100);
}

- (void) drawRect: (NSRect) rect {
	
	glViewport( 0, 0, (GLsizei) rect.size.width, (GLsizei) rect.size.height );

	glClearColor(0, .5, .8, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();
	
	glTranslatef( 0, 0, -1 );
	
	GLfloat green[ 4 ] = { 0, 1, 0, 0 };
	glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, green);
    glutSolidTeapot( .5 );
	
    [ [ self openGLContext ] flushBuffer ];	
    
}



@end
